<?php defined('BASEPATH') OR exit('No direct script access allowed');

if(session_id() == '') {
    // session isn't started
}


class Account_private extends wsFrontend
{
    public function __construct()
    {
        parent::__construct();
        if (strpos(strtolower($this->uri->uri_string()), 'account_private') !== false) {
            redirect(base_url());
        }
        $this->db->cache_off();
    }

    public function index()
    {
        if (!$this->user->is_loggedIn()) {
            redirect($this->route_links->build_link('account_login'));
        }
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_index_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_index_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_index_keywords', 'account');

        $this->load->helper('date');

        $this->tpl->breadcrumbs['用户中心'] = 'active';
        $this->tpl->contents [] = $this->tpl->fetch('contents/account_index', $data);
        $this->tpl->render('layouts/empty');
    }

    public function forgotten_password()
    {
        if ($this->user->is_loggedIn()) {
            redirect($this->referer('login'));
        }
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_reset_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_reset_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_reset_keywords', 'account');
        $this->tpl->disable_header_flash = true;
        $data['captcha'] = false;
        if ($this->config->item('enable_captcha')) {
            $data['captcha'] = true;
        }
        //Force Turn off captcha
        //$data['captcha'] = false;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('user_email','ddd');
        if ($data['captcha'])
            $this->form_validation->set_rules('recaptcha_response_field', $this->language->get_text('captcha-code', 'account'), 'required');
        $this->tpl->disable_header_flash = true;
        $data['error'] = $data['captchaError'] = false;
        if ($this->form_validation->run()) {
            $has_error = false;
            if ($data['captcha']) {
                $resp = recaptcha_check_answer('', $_SERVER["REMOTE_ADDR"], $this->input->post('recaptcha_challenge_field'), $this->input->post('recaptcha_response_field'));
                if (!$resp->is_valid) {
                    $data['captchaError'] = $resp->error;
                    $has_error = true;
                }
            }
            if (!$has_error) {
                $this->db->cache_off();
                $user = $this->user_model->get_userByEmail($this->input->post('user_email'));
                if ($user) {
                    $this->load->helper('string');
                    $pass = random_string();

                    $mail_data = array(
                        'title' => config_item('site_name') . ' - ' . $this->language->get_text('reset-password', 'account'),
                        'name' => $user->user_name,
                        'email' => $user->user_email,
                        'password' => $pass
                    );
                    $this->user_model->update_user(array('user_password' => ws_password_hash($pass)), array('user_seq_id' => $user->user_seq_id));

                    $mail_body = $this->tpl->fetch('mail/new-password', $mail_data);
                    $default_configs = array(
                        'mailtype' => 'html',
                        'charset' => 'utf-8',
                    );

                    $this->load->library('email');
                    $this->email->initialize($default_configs);
                    $this->email->from($this->config->item('contact_email'), config_item('site_name'));
                    $this->email->to($user->user_email);
                    $this->email->subject($data['title']);
                    $this->email->message($mail_body);
                    $this->email->send();
                    $this->session->set_flashdata('SUCCESS', $this->language->get_text('new-password-has-sent-to-your-mail', 'account'));
                    redirect($this->route_links->build_link('account_login'));
                } else {
                    $data['error'] = $this->language->get_text('email-address-not-exists-in-or-database', 'account');
                }
            }
        }
        $this->tpl->contents [] = $this->tpl->fetch('contents/account_reset_password', $data);
        $this->tpl->render('layouts/empty');
    }

    public function resend_activation()
    {
        $id = $this->session->tempdata('resend_activation_email');
        if ($id) {
            $user_id = $this->user_model->get_userById($id);
            if ($user_id) {
                $data = array(
                    'title' => config_item('site_name') . ' - ' . $this->language->get_text('activation-link', 'account'),
                    'name' => $user_id->user_name,
                    'email' => $user_id->user_email,
                    'code' => $user_id->user_emailCode,
                    'activation_link' => true,
                );

                $mail_body = $this->tpl->fetch('mail/welcome', $data);

                $this->session->set_flashdata('SUCCESS', $this->language->get_text('please-check-your-email-we-have-send-you-activation-code', 'account'));
                $default_configs = array(
                    'mailtype' => 'html',
                    'charset' => 'utf-8'
                );
                $this->load->library('email');
                $this->email->initialize($default_configs);
                $this->email->from($this->config->item('contact_email'), config_item('site_name'));
                $this->email->to($data['email']);
                $this->email->subject($data['title']);
                $this->email->message($mail_body);
                $this->email->send();
                $this->session->unset_tempdata('resend_activation_email');
            }
        }
        redirect($this->route_links->build_link('account_login'));
    }

    public function settings()
    {
        if (!$this->user->is_loggedIn()) {
            redirect($this->route_links->build_link('account_login'));
        }
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_settings_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_settings_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_settings_keywords', 'account');

        $this->load->library('form_validation');

        if (isset($_POST['password_update'])) {
            $this->form_validation->set_rules('old_password', $this->language->get_text('old-password', 'account'), 'required');
            $this->form_validation->set_rules('user_password', $this->language->get_text('user-password', 'account'), 'required|min_length[5]');
            $this->form_validation->set_rules('re_user_password', $this->language->get_text('re-type-password', 'account'), 'required|matches[user_password]');
        } elseif (isset($_POST['profile_update'])) {
            $this->form_validation->set_rules('user_name', $this->language->get_text('user-name', 'account'), 'required');
        }
        $data['error'] = false;
        if ($this->form_validation->run()) {
            $update_data = array();
            if (isset($_POST['password_update'])) {
                if (ws_password_hash($this->input->post('old_password')) != $this->user->get_value('user_password')) {
                    $data['error'] = 'Invalid Old Password';
                }
                if (!$data['error']) {
                    $update_data = array(
                        'user_password' => ws_password_hash($this->input->post('user_password'))
                    );
                }
            } elseif (isset($_POST['profile_update'])) {
                if (!$data['error']) {
                    $update_data = array(
                        'user_name' => $this->input->post('user_name'),
                        'user_public_profile' => ($this->input->post('user_public_profile') ? 1 : 0),
                    );
                }
            }
            if (!empty($update_data)) {
                $this->user_model->update_user($update_data, array('user_seq_id' => $this->user->get_id()));
                $this->session->set_flashdata('SUCCESS', $this->language->get_text('user-data-updated-successfully', 'account'));
                redirect($this->route_links->build_link('account_settings'));
            }
        }


        $this->tpl->breadcrumbs['用户中心'] = $this->route_links->build_link('account_index');
        $this->tpl->breadcrumbs['个人设置'] = 'active';
        $this->tpl->contents [] = $this->tpl->fetch('contents/account_settings', $data);
        $this->tpl->render('layouts/empty');
    }

    public function avatar()
    {
        if (!$this->user->is_loggedIn()) {
            redirect($this->route_links->build_link('account_login'));
        }
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_avatar_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_avatar_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_avatar_keywords', 'account');

        $data['error'] = $upload_data = $image = false;
        $data['min_size'] = 300;
        if (!empty($_POST) && isset($_FILES['user_profile_pic']['error']) && $_FILES['user_profile_pic']['error'] == UPLOAD_ERR_OK) {
            $config['upload_path'] = FULL_TEMP . DS . $this->user->get_id();
            if (!is_dir($config['upload_path']))
                mkdir($config['upload_path'], 0777, true);
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = MAX_SIZE;
            $config['overwrite'] = TRUE;
            $config['min_width'] = $data['min_size'];
            $config['min_height'] = $data['min_size'];
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('user_profile_pic')) {
                $data['error'] = $this->upload->display_errors();
            } else {
                $upload_data = $this->upload->data();
                $image = FULL_TEMP_RAW . DS . $this->user->get_id() . DS . $upload_data['file_name'];
            }
        }

        if (isset($_POST['upload_img']) && !$data['error'] && $image) {
            $filename = $this->hashids->encrypt($this->user->get_id(), time()) . '.jpg';
            $move = $this->image_workshop->resize_and_move($image, AVATAR_FOLDER_WF, $filename, $data['min_size'], $data['min_size']);
            if ($move) {
                $old_profile_pic = $this->user->get_value('user_profile_pic');
                if ($old_profile_pic && DELETE_OLD_AVATAR) {
                    @unlink(FCPATH . $old_profile_pic);
                }
                $this->session->set_flashdata('SUCCESS', $this->language->get_text('profile-pic-updated-successfully', 'account'));
                $update_data = array(
                    'user_profile_pic' => AVATAR_FOLDER_WF . '/' . $filename
                );
                $this->user_model->update_user($update_data, array('user_seq_id' => $this->user->get_id()));
            } else {
                $this->session->set_flashdata('ERROR', $this->language->get_text('unable-to-move-file', 'account'));
            }
            redirect(redirect($this->route_links->build_link('account_avatar')));
        }

        $this->tpl->breadcrumbs['用户中心'] = $this->route_links->build_link('account_index');
        $this->tpl->breadcrumbs['修改头像'] = 'active';
        $this->tpl->contents [] = $this->tpl->fetch('contents/account_avatar', $data);
        $this->tpl->render('layouts/empty');
    }

    public function logout()
    {
        $this->user->logOut();
        redirect($this->referer());
    }

    public function login()
    {
        if ($this->user->is_loggedIn()) {
            redirect($this->referer('login'));
        }
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_login_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_login_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_login_keywords', 'account');
        $this->tpl->disable_header_flash = true;
        $data['captcha'] = false;
        if ($this->config->item('enable_captcha')) {
            $data['captcha'] = true;
        }
        //Force Turn off captcha
        //$data['captcha'] = false;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('user_email', $this->language->get_text('user-email', 'account'), 'required|valid_email');
        $this->form_validation->set_rules('user_password', $this->language->get_text('user-password', 'account'), 'required');
        if ($data['captcha'])
            $this->form_validation->set_rules('recaptcha_response_field', $this->language->get_text('captcha-code', 'account'), 'required');

        $data['error'] = $data['captchaError'] = false;
        if ($this->form_validation->run()) {
            $has_error = false;
            if ($data['captcha']) {
                $resp = recaptcha_check_answer('', $_SERVER["REMOTE_ADDR"], $this->input->post('recaptcha_challenge_field'), $this->input->post('recaptcha_response_field'));
                if (!$resp->is_valid) {
                    $data['captchaError'] = $resp->error;
                    $has_error = true;
                }
            }
            if (!$has_error) {
                $this->db->cache_off();
                $user = $this->user_model->validateLogin($this->input->post('user_email'), $this->input->post('user_password'));

                if ($user) {
                    $hash_Error = false;
                    if ($this->config->item('user_email_confirm') && !$user->user_emailConfirm) {
                        $this->session->set_tempdata('resend_activation_email', $user->user_seq_id);
                        $data['error'] = $this->language->get_text('login_confirm_msg', 'account') . ' <a href="' . $this->route_links->build_link('account_resend_activation') . '">click here</a>';
                        $hash_Error = true;
                    }
                    if (!$hash_Error) {
                        $this->session->set_userdata('LAST_LOGIN', $user->user_lastLogin);
                        $this->user->setUser($user, isset($_POST['remember_me']) ? true : false);
                        $this->UpdateLast_login($user->user_seq_id);
                        redirect($this->referer());
                    }
                } else {
                    $data['error'] = $this->language->get_text('invalid-username/password', 'account');
                }
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/account_login', $data);
        $this->tpl->render('layouts/empty');
    }

    public function signUp()
    {
        if ($this->user->is_loggedIn()) {
            redirect($this->referer('signup'));
        }

        if ($this->config->item('disable_registration')) {
            $this->session->set_flashdata('ERROR', $this->language->get_text('registration-has-disabled', 'account'));
            redirect($this->route_links->build_link('account_login'));
        }

        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_signUp_title', 'account');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_signUp_description', 'account');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_signUp_keywords', 'account');

        $data['captcha'] = false;
        if ($this->config->item('enable_captcha')) {
            $data['captcha'] = true;
        }

        //Force Turn off captcha
        //$data['captcha'] = false;

        $this->load->library('form_validation');
        $this->form_validation->set_rules('user_email', $this->language->get_text('user-email', 'account'), 'required|valid_email');
        $this->form_validation->set_rules('user_password', $this->language->get_text('user-password', 'account'), 'required|min_length[5]');
        $this->form_validation->set_rules('user_name', $this->language->get_text('user-name', 'account'), 'required');
        $this->form_validation->set_rules('re_user_password', $this->language->get_text('re-type-password', 'account'), 'required|matches[user_password]');
        if ($data['captcha'])
            $this->form_validation->set_rules('recaptcha_response_field', $this->language->get_text('captcha-code', 'account'), 'required');

        $data['error'] = $data['captchaError'] = false;
        if ($this->form_validation->run()) {
            $has_error = false;
            if ($data['captcha']) {
                $resp = recaptcha_check_answer('', $_SERVER["REMOTE_ADDR"], $this->input->post('recaptcha_challenge_field'), $this->input->post('recaptcha_response_field'));
                if (!$resp->is_valid) {
                    $data['captchaError'] = $resp->error;
                    $has_error = true;
                }
            }
            if (!$has_error) {
                $this->db->cache_off();
                $Email_exists = $this->user_model->get_userByEmail($this->input->post('user_email'));
                if (!$Email_exists) {
                    $insert_data = array(
                        'user_email' => $this->input->post('user_email'),
                        'user_password' => ws_password_hash($this->input->post('user_password')),
                        'user_name' => $this->input->post('user_name'),
                        'user_created' => date('Y:m:d H:i:s'),
                        'user_emailConfirm' => 0,
                        'user_emailCode' => sha1(uniqid()),
                        'user_status_seq_id' => 1,
                        'user_type_seq_id' => 1,
                    );
                    $this->user_model->insert($insert_data);
                    $msg = '注册成功';
                    $this->sendMail($insert_data, true);
                    if ($this->config->item('user_email_confirm')) {
                        $msg = $this->language->get_text('acc_created_success', 'account');
                    }
                    $this->session->set_flashdata('SUCCESS', $msg);
                    redirect($this->route_links->build_link('account_login'));
                } else {
                    $data['error'] = $this->language->get_text('sorry', 'global') . '! "' . $this->input->post('user_email') . '" ' . $this->language->get_text('email-already-exists-in-database', 'account');
                }
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/account_signUp', $data);
        $this->tpl->render('layouts/empty');
    }

    private function sendMail($user_data, $activation_link = true)
    {
        $data = array(
            'title' => config_item('site_name') . ' - '.$this->language->get_text('welcome-email/activation','mail'),
            'name' => $user_data['user_name'],
            'email' => $user_data['user_email'],
            'code' => $user_data['user_emailCode'],
            'activation_link' => $activation_link,
        );

        $mail_body = $this->tpl->fetch('mail/welcome', $data);

        $default_configs = array(
            'mailtype' => 'html',
            'charset' => 'utf-8'
        );
        $this->load->library('email');
        $this->email->initialize($default_configs);
        $this->email->from($this->config->item('contact_email'), config_item('site_name'));
        $this->email->to($data['email']);
        $this->email->subject($data['title']);
        $this->email->message($mail_body);
        $this->email->send();
    }

    public function verify()
    {
        $this->db->cache_off();
        $email = $this->input->get('email');
        $code = $this->input->get('code');

        $this->db->where('user_emailCode', $code);
        $user = $this->user_model->get_userByEmail($email);

        if ($user) {
            if ($user->user_emailConfirm) {
                $this->session->set_flashdata('SUCCESS', $this->language->get_text('email-already-activated','mail'));
            } else {
                $update_data = array(
                    'user_emailConfirm' => 1
                );
                $this->user_model->update_user($update_data, array('user_seq_id' => $user->user_seq_id));
                $this->session->set_flashdata('SUCCESS', $this->language->get_text('email-activated-successfully','mail'));
            }
        } else {
            $this->session->set_flashdata('SUCCESS', $this->language->get_text('invalid-activation-code','mail'));
        }
        redirect($this->route_links->build_link('account_login'));
    }


    private function UpdateLast_login($userID)
    {
        $update = array(
            'user_lastLogin' => date('Y-m-d H:i:s')
        );
        $this->user_model->update_user($update, array('user_seq_id' => $userID));
    }

    public function wallpapers($type = '')
    {
        $type = strtolower($type);
        $allowed = array(
            'uploaded', 'favourites', 'likes', 'dislikes', 'downloads'
        );
        if (!in_array($type, $allowed))
            $type = 'uploaded';
        $data['type'] = $type;

        $filter['bypath'] = false;
        $filter['cacheoff'] = true;
        $filter['show_disabled'] = true;

        if ($type == 'uploaded')
            $filter['where_user_id'] = $this->user->get_id();

        if ($type != 'uploaded') {
            $filter['by_user_' . $type] = $this->user->get_id();
        }

        $data['url'] = current_url();
        $this->load->model(array('wallpaper_model'));


        $filter['per_page'] = $config['per_page'] = $this->config->item('items_per_page');
        $page_number = (int)$this->input->get('page');
        $filter['offset'] = ($page_number ? ($page_number - 1) * $config['per_page'] : 0);

        $data['total_count'] = $this->wallpaper_model->getWallpapers($filter + array('count' => true));

        //Initialize Pagination
        $config['base_url'] = $data['url'];
        $config['total_rows'] = $data['total_count'];
        $config['custom_query_string'] = TRUE;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'page';

        if (!empty($_GET)) {
            $get_method = $this->frontend_helper->get_query_string(array('page'));
            $config['prefix'] = ($get_method ? $get_method . '&' : '?') . 'page=';
            $config['first_url'] = $config['base_url'] . $get_method;
        } else {
            $config['prefix'] = '?page=';
        }

        $this->load->library('pagination');
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['wallpapers'] = $this->wallpaper_model->getWallpapers($filter);


        $this->tpl->breadcrumbs['用户中心'] = $this->route_links->build_link('account_index');
        $this->tpl->breadcrumbs['我的壁纸'] = 'active';

        $search_replace = array('{type}' => ucwords($type));
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_account_wallpapers_title', 'account', $search_replace, false, $page_number);
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_account_wallpapers_description', 'account', $search_replace, false, $page_number);
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_account_wallpapers_keywords', 'account', $search_replace, false, $page_number);

        $this->tpl->contents [] = $this->tpl->fetch('contents/account_wallpapers', $data);
        $this->tpl->render('layouts/empty');
    }
}
